package com.suzhouhe.util.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ip工具类
 *
 * @author suzhouhe
 * @date 2020-12-09 11:22
 **/
public class IpUtil {

    private static final String HEADER_FORWARDED = "x-forwarded-for";

    private static final String UNKNOWN = "unknown";

    private static final String HEADER_PROXY = "Proxy-Client-IP";

    private static final String HEADER_WL = "WL-Proxy-Client-IP";

    private static final String LOCAL_IP = "127.0.0.1";

    private static final String DELIMITER = ",";

    /**
     * 获取用户请求的ip地址
     *
     * @param request request
     * @return ip地址信息
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress;
        try {
            ipAddress = request.getHeader(HEADER_FORWARDED);
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader(HEADER_PROXY);
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader(HEADER_WL);
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (LOCAL_IP.equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    try {
                        ipAddress = InetAddress.getLocalHost().getHostAddress();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null) {
                if (ipAddress.contains(DELIMITER)) {
                    return ipAddress.split(DELIMITER)[0];
                } else {
                    return ipAddress;
                }
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
